package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func Post(client *http.Client, url string, data interface{}, contentType string) ([]byte, error) {
	if client == nil {
		client = &http.Client{Timeout: 3 * time.Second}
	}
	jsonStr, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		return nil, err
	}
	//if resp.StatusCode != http.StatusOK {
	//	return nil, errors.New("Request failed")
	//}
	defer resp.Body.Close()

	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func Get(client *http.Client, url string, params map[string]interface{}) ([]byte, error) {
	if client == nil {
		client = &http.Client{Timeout: 3 * time.Second}
	}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	q := req.URL.Query()
	for k, v := range params {
		q.Add(k, fmt.Sprintf("%v", v))
	}
	req.URL.RawQuery = q.Encode()
	//fmt.Println(req.URL.String())
	resp, err := client.Get(req.URL.String())
	if err != nil {
		return nil, err
	}
	//if resp.StatusCode != http.StatusOK {
	//	return nil, errors.New("Request failed")
	//}
	defer resp.Body.Close()
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func Put(client *http.Client, url string, data interface{}, contentType string) ([]byte, error) {
	if client == nil {
		client = &http.Client{Timeout: 3 * time.Second}
	}
	jsonStr, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", contentType)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func Delete(client *http.Client, url string, data interface{}, contentType string) ([]byte, error) {
	if client == nil {
		client = &http.Client{Timeout: 3 * time.Second}
	}
	jsonStr, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("DELETE", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", contentType)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return result, nil
}
